const express = require("express");
const createError = require("http-errors");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
//日志
const fs = require("fs");
const path = require("path");
const moment = require("moment");
//session和redis
const session = require("express-session");
const RedisStore = require("connect-redis")(session);
const redisClient = require("./db/redis");

//引入路由
const userRouter = require("./routes/user");
const blogRouter = require("./routes/blog");

const app = express();

//处理日志
if (process.env.NODE_ENV === "development") {
    //开发环境
    app.use(logger("dev"));
} else {
    //线上环境
    let time = moment().format("YYYY-MM-DD");
    let fileName = time + ".access.log";
    let filePath = path.join(__dirname, "./logs/", fileName);

    const writeStream = fs.createWriteStream(filePath, {
        flags: "a"
    });
    app.use(logger("combined", {
        stream: writeStream
    }))
}

//处理JSON格式的Post数据
app.use(express.json());
//处理x-www-form-urlencoded格式的POST数据
app.use(express.urlencoded({ extended: false }));
//处理Cookie
app.use(cookieParser());
//处理session
app.use(session({
    name: "lvye", 
    //密钥
    secret: "helicopter",
    cookie: {
        path: "/",            //默认配置
        httpOnly: true,       //默认配置
        maxAge: 7 * 24 * 60 * 60 * 1000
    },
    store: new RedisStore({
        client: redisClient
    }),
    resave: false,
    saveUninitialized: true
}))

//处理路由
app.use("/api/user", userRouter);
app.use("/api/blog", blogRouter);

//处理404
// app.use(function (req, res, next) {
//     next(createError(404));
// });
app.use("*", (req, res, next) => {
    res.sendfile("./pages/404.html");
})

//处理错误
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get("env") === "development" ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render("error");
});

module.exports = app;